package com.tungse.juc.product_consumers;

public class PCDemo {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();//生产者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();//消费者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();//生产者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();//消费者
    }

}


//执行顺序   等待  业务  通知
class Data {//资源类
    private int num = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        while (num != 0) {
        //等待
            this.wait();
        }
        num++;//业务
        System.out.println(Thread.currentThread().getName() + "=>" + num);
        //通知其他线程， 生产完毕了
        this.notify();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (num == 0) {
        //等待
            this.wait();
        }
        num--;//业务
        System.out.println(Thread.currentThread().getName() + "=>" + num);
        //通知其他线程， 消费完毕了
        this.notify();
    }
}